import os
import time
from seleniumwire import webdriver
# from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.options import Options

from configs.configs import root_path, HEADERS

before = 'before.png'
after = 'after.png'


def wait_element(brower, element_id, wait_time=10):
    try:

        WebDriverWait(brower, wait_time, 1).until(
            EC.presence_of_element_located((By.ID, element_id))
        )
    except Exception as e:
        raise Exception(e)


def wait_element_css(brower, css, wait_time=10):
    try:
        WebDriverWait(brower, wait_time, 1).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, css))
        )
    except Exception as e:
        raise Exception(e)


def get_brower_header(brower):
    all_header_info = []
    for request in brower.requests:
        req_url = request.url
        req_headers = dict(request.headers)
        resp_headers = dict(request.response.headers)
        data = {
            'req_url': req_url,
            'req_headers': req_headers,
            'resp_headers': resp_headers
        }
        all_header_info.append(data)
    return all_header_info


def add_header(headers):
    options = Options()
    for k, v in headers.items():
        options.add_argument(f'{k}={v}')
    return options


def disable_img_css(options):
    # 禁止图片
    prefs = {"profile.managed_default_content_settings.images": 2,
             }
    options.add_experimental_option("prefs", prefs)


def disable_css(options):
    # 禁止css加载
    prefs = {'permissions.default.stylesheet': 2}
    options.add_experimental_option("prefs", prefs)


def brower_headless(options):
    # 无头浏览器
    options.add_argument('headless')


def get_brower(headers=None, stealth=True, disable_img=False, disable_css=False, headless=False):
    if not headers:
        headers = HEADERS
    options = add_header(headers)
    if headless:
        brower_headless(options)
    brower = webdriver.Chrome(executable_path='chromedriver', chrome_options=options)

    if stealth:
        js_path = os.path.join(root_path, 'js', 'stealth.min.js')
        with open(js_path) as f:
            js = f.read()

        # 在打印具体的网页前，执行隐藏浏览器特征的JavaScript
        brower.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": js
        })
    return brower
